import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/config/theme.dart';

///
/// 文本添加超链接
///
class CustomRichText extends GetView {
  /// 完整文本
  final String? fullText;

  /// 超链接文本列表
  final List<String>? linkTextList;

  final int? maxLines;

  final TextOverflow? overflow;

  /// 默认字体大小
  final double? fontSize;

  final TextStyle? defaultTextStyle;

  final TextStyle? highlightTextStyle;

  /// 是否响应交互，默认未true
  final bool userInteractionEnabled;

  final void Function(int index)? onTap;
  const CustomRichText(
      {super.key,
      required this.fullText,
      required this.linkTextList,
      this.maxLines,
      this.overflow,
      this.fontSize,
      this.defaultTextStyle,
      this.highlightTextStyle,
      this.userInteractionEnabled = true,
      this.onTap});

  @override
  Widget build(BuildContext context) {
    ///
    /// Text的textScaleFactor默认为MediaQueryData.textScaleFactor
    /// RichText的textScaleFactor默认为1.0
    /// 当更改系统字体大小时，为了让字体大小保持一致（等比缩放），需要把RichText的textScaleFactor与Text改成一致
    ///
    // return RichText(
    //   maxLines: maxLines ?? 100,
    //   overflow: overflow ?? TextOverflow.ellipsis, // 超出显示省略号
    //   textScaleFactor: MediaQueryData.fromWindow(WidgetsBinding.instance.window)
    //       .textScaleFactor,
    //   text: TextSpan(
    //     children: buildTextContent(context),
    //   ),
    // );
    return AutoSizeText.rich(
      TextSpan(children: buildTextContent(context)),
      maxLines: maxLines ?? 100,
      minFontSize: 8,
      overflow: overflow ?? TextOverflow.ellipsis, // 超出显示省略号
      textScaleFactor:
          WidgetsBinding.instance.platformDispatcher.textScaleFactor,
    );
  }

  List<InlineSpan> buildTextContent(BuildContext context) {
    TextStyle defaultStyle = defaultTextStyle ??
        TextStyle(
            fontSize: fontSize ?? 13.0, color: lxColorScheme.subtitleColor);
    TextStyle highlightStyle = highlightTextStyle ??
        TextStyle(
            fontSize: fontSize ?? 13.0, color: lxColorScheme.linkTextColor);

    if (fullText == null || linkTextList == null) {
      return [TextSpan(text: fullText, style: defaultTextStyle)];
    }

    String linkString = linkTextList!.join('|');
    String newString = formatString(linkString);

    // 使用正则匹配字符串，修改字体样式并添加手势
    RegExp exp = RegExp(newString);
    Iterable<RegExpMatch> matches = exp.allMatches(fullText!);

    List<InlineSpan> contentList = [];

    int index = 0;
    for (var match in matches) {
      String value = fullText!.substring(match.start, match.end);
      if (match.start == index) {
        index = match.end;
      }
      // 开头文本样式
      if (index < match.start) {
        String startText = fullText!.substring(index, match.start);
        index = match.end;
        contentList.add(TextSpan(
          text: startText,
          style: defaultStyle,
        ));
      }

      if (linkTextList!.contains(value)) {
        contentList.add(TextSpan(
          recognizer: TapGestureRecognizer()
            ..onTap = userInteractionEnabled == true
                ? () {
                    debugPrint('点击了关键词');
                    if (onTap != null) {
                      onTap!(linkTextList!.indexOf(value));
                    }
                  }
                : null,
          text: value,
          style: highlightStyle,
        ));
      }
    }

    // 结尾文本样式
    if (index < fullText!.length) {
      String a = fullText!.substring(index, fullText!.length);
      contentList.add(TextSpan(text: a, style: defaultStyle));
    }

    return contentList;
  }

  String formatString(String value) {
    List symbolList = ['*', '+', '.', ',', '?', '-', '='];
    for (var symbol in symbolList) {
      value = value.replaceAll(symbol, "\\$symbol");
    }

    return value;
  }
}
